# coding:utf-8
# 文件分析-统计字符出现此次与频率
# 2017-1-25 01:19:00
# v：0.2
import os
# 配置：
config = {"mode": 0,
          "inPath": "F:\\py_test\\小说\\诛仙.txt",
          "outPath": "./Fana.dat",
          # 'path':'./pyFile.txt',
          "keyword": None,

          }
# 忽略统计的字符
ig = ['\n', '\t', ' ']
# 数据分析结果
saData = {}

# 获取一个文件全部内容


def fGet(fileUrl):
    fp = open(fileUrl, errors='ignore')
    if not fp:
        print('文件路径错误')
    fStr = fp.read()
    fp.close()
    return fStr

# 写入文件


def fPut(fileUrl, wStr, mode='a'):
    fp = open(fileUrl, mode)
    if not fp:
        print('文件写入失败')
    wRes = fp.write(wStr)
    fp.close()
    return wRes


res = fGet(config['inPath'])  # 读取文件全部内容
saData['wordsNum'] = 0  # 初始化字数
saData['distrib'] = {}  # 初始化统计池
# 迭代统计
for x in res:
    if x in ig:  # 忽略统计(跳过忽略)
        continue
    if x in saData['distrib']:
        saData['distrib'][x] += 1
    else:
        saData['distrib'][x] = 1
    saData['wordsNum'] += 1
# 计算频率
for k in saData['distrib']:
    ratio = float(saData['distrib'][k]) / saData['wordsNum']
    one = {'amount': saData['distrib'][k], 'ratio': ratio}
    saData['distrib'][k] = one

# 降序排序
wTemp = sorted(saData['distrib'].items(), key=lambda a: a[
               1]['amount'], reverse=True)

# 输出
fPut(config['outPath'], '----------- 文本字数统计分析器 \n', mode='w')
fName = os.path.basename(config['inPath'])
pStr = '----------- 文件名：《%s》 总字数：（%d） 种类数：%d \n' % (
    fName, saData['wordsNum'], len(saData['distrib']))
fPut(config['outPath'], pStr)
i = 0
for x in wTemp:
    pStr = "%s : %06d(%1.3f%%)  |  " % (
        x[0], x[1]['amount'], x[1]['ratio'] * 100)
    i += 1
    if i >= 5:
        i = 0
        pStr += '\n'
    fPut(config['outPath'], pStr)
